package com.yh.homestay.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName WebSecurityConfig
 * @Description 安全框架Config
 * @Author GCL
 * @Date 2020/1/6 9:27
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder myPasswordEncoder;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                .disable()//拦截跨站请求
                .authorizeRequests()
                .antMatchers("/no-permission","/login").permitAll()//允许匿名访问的url
                .antMatchers("/room/list","/","/welcome1").hasAnyAuthority("ROLE_USER","ROLE_ADMIN","ROLE_BOSS")
                .antMatchers("/room/update","/room/add").hasAnyAuthority("ROLE_BOSS","ROLE_ADMIN")
                .antMatchers("/room/delete","/room/deleteBatch").hasAuthority("ROLE_BOSS")
                .and()
                .formLogin()
                .loginPage("/login")//跳转登录页面
                .successForwardUrl("/")//验证成功跳转页面
                .failureForwardUrl("/no-permission")//验证失败跳转页面
                .usernameParameter("staffId")//修改表单中用户名name属性
                .passwordParameter("staffName")//修改表单中密码name属性
                .and()
                .logout()
//                .permitAll();
                .logoutUrl("/logout")//自定义登出
                .logoutSuccessUrl("/login");//登出成功跳转页面
        http.headers().frameOptions().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(myPasswordEncoder);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //放行静态资源
        web.ignoring().antMatchers("/css/**","/fonts/**","/js/**","/lib/**","/images/**");
    }

}
